package com.codedog.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.codedog.constant.ExcelTitleConstant;
import com.codedog.constant.HomeWorkStatusConstant;
import com.codedog.constant.UrlConstant;
import com.codedog.constant.VoiceWeeklyStatusConstant;
import com.codedog.entity.ExcelStudent;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.util.*;


public class CodeDogExcelUtil {

    public static List<ExcelStudent> getStudentsByExcel(String url) {
        List<ExcelStudent> studentsList = new LinkedList<>();
        ExcelReader reader = ExcelUtil.getReader(url);
        List<Map<String, Object>> readAll = reader.readAll();
        for (Map<String, Object> studentMap : readAll) {
            ExcelStudent excelStudentBean = new ExcelStudent();
            excelStudentBean.setId(StrUtil.toString(studentMap.get(ExcelTitleConstant.ID)));
            excelStudentBean.setName(StrUtil.toString(studentMap.get(ExcelTitleConstant.NAME)));
            studentsList.add(excelStudentBean);
        }
        reader.close();
        return studentsList;
    }


    public static void writeExcel(ArrayList<Map<String, Object>> rows, String fileName) {
        String exportExcel = getDesktop() + UrlConstant.EXPORT_EXCEL_DIRECTORY + fileName;
        if (!CollectionUtil.isEmpty(rows)) {
            File file = FileUtil.file(exportExcel);
            ExcelWriter writer = null;
            FileUtil.del(file);
            writer = ExcelUtil.getWriter(exportExcel);
            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(ExcelTitleConstant.COLUMN_SIZE, ExcelTitleConstant.TABLE_NAME);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(rows, true);
            // 关闭writer，释放内存
            writer.close();
            System.out.println("导出文件成功！文件目录：" + exportExcel);
        } else {
            System.out.println("数据为空，不需要导入");
        }
    }


    public static String writeExcelByDate(ArrayList<Map<String, Object>> rows, String fileName) throws Exception {
        String exportExcel = getDesktop() + UrlConstant.EXPORT_EXCEL_DIRECTORY + DateUtil.formatDate(DateUtil.date()) + UrlConstant.URL_LAST02 + fileName;
        if (!CollectionUtil.isEmpty(rows)) {
            Map<String, Object> rowMap = rows.get(0);
            File file = FileUtil.file(exportExcel);
            ExcelWriter writer = null;
            FileUtil.del(file);
            writer = ExcelUtil.getWriter(exportExcel);
            // 合并单元格后的标题行，使用默认标题样式
            writer.merge(rowMap.size() - 1, ExcelTitleConstant.TABLE_NAME);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(rows, true);
            // 关闭writer，释放内存
            writer.close();
            System.out.println("导出文件成功！文件目录：" + exportExcel);
        } else {
            System.out.println("数据为空，不需要导入");
        }
        return exportExcel;
    }

    public static void updateExcelRowBackgroundColor(ArrayList<Map<String, Object>> rows, String fileName) throws Exception {
        String excelUrl = writeExcelByDate(rows, fileName);
        List<Integer> rowList = getRowList(rows);
        if (CollectionUtil.isEmpty(rows)) {
            return;
        }
        // 读取Excel文件
        FileInputStream fis = new FileInputStream(excelUrl);
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);
        // 创建样式对象
        CellStyle style = workbook.createCellStyle();
        // 设置填充颜色为黄色
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置文本水平居中对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        // 设置文本垂直居中对齐
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置单元格边框
        setCellBorder(style);
        // 将样式应用到该行的所有单元格
        for (int i = 0; i < rowList.size(); i++) {

            // 获取要设置颜色和对齐方式的行
            Row row = sheet.getRow(rowList.get(i));
            if (row == null) {
                row = sheet.createRow(rowList.get(i));
            }
            for (Cell cell : row) {
                if (cell == null) {
                    cell = row.createCell(row.getLastCellNum());
                }
                cell.setCellStyle(style);
            }
        }
        // 写入修改后的Excel文件
        FileOutputStream fos = new FileOutputStream(excelUrl);
        workbook.write(fos);
        fos.close();
        fis.close();

    }

    private static List<Integer> getRowList(ArrayList<Map<String, Object>> rows) {
        List<Integer> rowList = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            //对应的一个学员信息，key是第二行，value是值
            Map<String, Object> rowMap = rows.get(i);
            if (rowMap.get(ExcelTitleConstant.TITLE_XSND).equals(HomeWorkStatusConstant.TOB_STATUS_NOT) || rowMap.get(ExcelTitleConstant.TITLE_TZCZ).equals(HomeWorkStatusConstant.HOMEWORK_STATUS_NOT)) {
                int rowIndex = i + 2;
                rowList.add(rowIndex);
            }
        }
        return rowList;
    }

    private static void setCellBorder(CellStyle style) {
        // 设置边框样式
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        // 设置边框颜色
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    }

    /**
     * 获取本机桌面路径
     *
     * @return
     */
    public static String getDesktop() {
        //当前用户桌面路径
        File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
        String desktopPath = desktopDir.getAbsolutePath();
        return desktopPath + UrlConstant.URL_LAST02;
    }

    /**
     * 添加水军数据
     *
     * @param rows
     */
    public static void updateAdminRows(ArrayList<Map<String, Object>> rows, Integer serialNumber) {
        List<String> nameList = List.of("文耀", "陈梓阳", "夏梓辰", "李安琪", "宋子豪", "钱庄", "李程");
        for (int i = 0; i < nameList.size(); i++) {
            Map<String, Object> row = new HashMap<>();
            row.put(ExcelTitleConstant.TITLE_ID, "");
            row.put(ExcelTitleConstant.TITLE_SERIAL_NUMBER, serialNumber);
            serialNumber++;
            row.put(ExcelTitleConstant.TITLE_USERNAME, nameList.get(i));
            row.put(ExcelTitleConstant.TITLE_LESSON_NAME, "");
            //课后闯关
            row.put(ExcelTitleConstant.TITLE_XSND, HomeWorkStatusConstant.TOB_STATUS_DONE);
            //拓展创作
            row.put(ExcelTitleConstant.TITLE_TZCZ, HomeWorkStatusConstant.HOMEWORK_STATUS_DONE03);
            //作业点评
            row.put(ExcelTitleConstant.TITLE_ZYDP, HomeWorkStatusConstant.WORK_STATUS_TEACHER_DONE);
            //语音周报
            row.put(ExcelTitleConstant.TITLE_SJKYYZB, VoiceWeeklyStatusConstant.OPENED_CHINESE);
            row.put(ExcelTitleConstant.TITLE_BYYYZB, VoiceWeeklyStatusConstant.OPENED_CHINESE);
            rows.add(row);
        }
    }

}
